"""
基础日志配置模块
==============

从 shared/core/config/service_logging/service_logging.py 提取的无依赖日志功能。
提供最基础的日志配置和管理功能，不依赖其他内部模块。
"""

import logging
import logging.config
import os
import sys
from pathlib import Path
from typing import Dict, Any, Optional, List
from enum import Enum


class LogLevel(str, Enum):
    """日志级别枚举"""
    DEBUG = "DEBUG"
    INFO = "INFO"
    WARNING = "WARNING"
    ERROR = "ERROR"
    CRITICAL = "CRITICAL"


class ServiceLoggingConfig:
    """微服务日志配置类"""
    
    def __init__(
        self,
        service_name: str,
        service_version: str = "1.0.0",
        environment: str = "development",
        log_level: str = "INFO",
        log_format: str = "detailed",
        enable_file_logging: bool = True,
        log_directory: str = "logs",
        enable_console_colors: bool = True,
        third_party_level: str = "WARNING"
    ):
        self.service_name = service_name
        self.service_version = service_version
        self.environment = environment
        self.log_level = self._validate_level(log_level)
        self.log_format = log_format
        self.enable_file_logging = enable_file_logging
        self.log_directory = Path(log_directory)
        self.enable_console_colors = enable_console_colors
        self.third_party_level = self._validate_level(third_party_level)
        
        # 从环境变量读取配置
        self._load_from_env()
        
        # 确保日志目录存在
        if self.enable_file_logging:
            try:
                self.log_directory.mkdir(exist_ok=True, parents=True)
            except (FileExistsError, OSError):
                pass
    
    def _validate_level(self, level: str) -> str:
        """验证日志级别"""
        level = level.upper()
        if level in [l.value for l in LogLevel]:
            return level
        return "INFO"
    
    def _load_from_env(self):
        """从环境变量加载配置"""
        env_prefix = f"{self.service_name.upper().replace('-', '_')}_"
        
        self.log_level = os.getenv(f"{env_prefix}LOG_LEVEL", self.log_level)
        self.log_format = os.getenv(f"{env_prefix}LOG_FORMAT", self.log_format)
        self.enable_file_logging = os.getenv(f"{env_prefix}ENABLE_FILE_LOG", str(self.enable_file_logging)).lower() == "true"
        self.log_directory = Path(os.getenv(f"{env_prefix}LOG_DIR", str(self.log_directory)))
        self.enable_console_colors = os.getenv(f"{env_prefix}CONSOLE_COLORS", str(self.enable_console_colors)).lower() == "true"
        self.third_party_level = os.getenv(f"{env_prefix}THIRD_PARTY_LOG_LEVEL", self.third_party_level)
    
    def get_formatters(self) -> Dict[str, Dict[str, Any]]:
        """获取格式化器配置"""
        formatters = {
            "simple": {
                "format": "%(levelname)s - %(message)s"
            },
            "detailed": {
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            },
            "structured": {
                "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s [%(filename)s:%(lineno)d]"
            },
            "service": {
                "format": f"%(asctime)s [{self.service_name}] [%(levelname)s] %(name)s: %(message)s"
            }
        }
        
        # 如果启用了控制台颜色，尝试添加彩色格式化器
        if self.enable_console_colors:
            try:
                import colorlog
                formatters["colored"] = {
                    "()": "colorlog.ColoredFormatter",
                    "format": "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                    "log_colors": {
                        'DEBUG': 'cyan',
                        'INFO': 'green',
                        'WARNING': 'yellow',
                        'ERROR': 'red',
                        'CRITICAL': 'red,bg_white',
                    }
                }
            except ImportError:
                pass
        
        return formatters
    
    def get_handlers(self) -> Dict[str, Dict[str, Any]]:
        """获取处理器配置"""
        handlers = {}
        
        # 控制台处理器
        console_formatter = "detailed"
        if self.enable_console_colors:
            try:
                import colorlog
                console_formatter = "colored"
            except ImportError:
                console_formatter = "detailed"
        
        handlers["console"] = {
            "class": "logging.StreamHandler",
            "level": self.log_level,
            "formatter": console_formatter,
            "stream": "ext://sys.stdout"
        }
        
        # 文件处理器
        if self.enable_file_logging:
            try:
                self.log_directory.mkdir(parents=True, exist_ok=True)
            except (FileExistsError, OSError):
                pass
            
            normalized_service_name = self.service_name.upper().replace('-', '_')
            
            log_file = self.log_directory / f"{normalized_service_name}.log"
            handlers["file"] = {
                "class": "logging.handlers.RotatingFileHandler",
                "level": self.log_level,
                "formatter": "service",
                "filename": str(log_file),
                "maxBytes": 10 * 1024 * 1024,  # 10MB
                "backupCount": 5,
                "encoding": "utf-8"
            }
            
            error_log_file = self.log_directory / f"{normalized_service_name}_error.log"
            handlers["error_file"] = {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "ERROR",
                "formatter": "structured",
                "filename": str(error_log_file),
                "maxBytes": 10 * 1024 * 1024,  # 10MB
                "backupCount": 10,
                "encoding": "utf-8"
            }
        
        return handlers
    
    def get_loggers_config(self) -> Dict[str, Dict[str, Any]]:
        """获取logger配置"""
        handlers = ["console"]
        if self.enable_file_logging:
            handlers.extend(["file", "error_file"])
        
        loggers = {
            "": {
                "level": self.log_level,
                "handlers": handlers
            },
            
            self.service_name: {
                "level": self.log_level,
                "handlers": handlers,
                "propagate": False
            },
            
            # 第三方库logger
            "sqlalchemy.engine": {
                "level": self.third_party_level,
                "handlers": handlers,
                "propagate": False
            },
            "uvicorn": {
                "level": self.third_party_level,
                "handlers": handlers,
                "propagate": False
            },
            "aioredis": {
                "level": self.third_party_level,
                "handlers": handlers,
                "propagate": False
            }
        }
        
        return loggers
    
    def get_logging_config(self) -> Dict[str, Any]:
        """获取完整的日志配置"""
        return {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": self.get_formatters(),
            "handlers": self.get_handlers(),
            "loggers": self.get_loggers_config()
        }


class ServiceLogger:
    """微服务日志管理器"""
    
    def __init__(self, config: ServiceLoggingConfig):
        self.config = config
        self._setup_logging()
        self.logger = logging.getLogger(config.service_name)
    
    def _setup_logging(self):
        """设置日志配置"""
        logging_config = self.config.get_logging_config()
        logging.config.dictConfig(logging_config)
    
    def get_logger(self, name: Optional[str] = None) -> logging.Logger:
        """获取logger实例"""
        if name:
            return logging.getLogger(f"{self.config.service_name}.{name}")
        return self.logger
    
    def log_startup(self, port: Optional[int] = None, **kwargs):
        """记录服务启动信息"""
        self.logger.info(f"🚀 {self.config.service_name} v{self.config.service_version} 启动中...")
        self.logger.info(f"📊 运行环境: {self.config.environment}")
        self.logger.info(f"📝 日志级别: {self.config.log_level}")
        
        if port:
            self.logger.info(f"📡 监听端口: {port}")
        
        if self.config.enable_file_logging:
            log_file = self.config.log_directory / f"{self.config.service_name}.log"
            self.logger.info(f"📄 日志文件: {log_file}")
        
        for key, value in kwargs.items():
            self.logger.info(f"🔧 {key}: {value}")
    
    def log_shutdown(self):
        """记录服务关闭信息"""
        self.logger.info(f"🛑 {self.config.service_name} 正在关闭...")
    
    def log_error(self, error: Exception, context: str = ""):
        """记录错误信息"""
        error_msg = f"❌ 错误: {str(error)}"
        if context:
            error_msg += f" (上下文: {context})"
        
        self.logger.error(error_msg, exc_info=True)


# 便捷函数
def setup_service_logging(
    config_or_service_name,
    service_version: str = "1.0.0",
    environment: str = None,
    **kwargs
) -> ServiceLogger:
    """设置服务日志并返回ServiceLogger实例"""
    
    if isinstance(config_or_service_name, dict):
        # 如果传入的是配置字典
        logging_config = config_or_service_name
        service_name = logging_config.get('service_prefix', 'DEFAULT')
        
        config_kwargs = {
            'log_level': logging_config.get('level', 'INFO'),
            'log_directory': logging_config.get('dir', './logs'),
            'log_format': 'json' if logging_config.get('format') == 'json' else 'detailed'
        }
        config_kwargs.update(kwargs)
        
        config = ServiceLoggingConfig(
            service_name=service_name,
            service_version=service_version,
            environment=environment or os.getenv("ENVIRONMENT", "development"),
            **config_kwargs
        )
    else:
        # 如果传入的是服务名称字符串
        service_name = config_or_service_name
        
        if environment is None:
            environment = os.getenv("ENVIRONMENT", "development")
        
        config = ServiceLoggingConfig(
            service_name=service_name,
            service_version=service_version,
            environment=environment,
            **kwargs
        )
    
    return ServiceLogger(config)


def get_service_logger(service_name: str, module_name: str = None) -> logging.Logger:
    """获取服务logger实例"""
    if module_name:
        return logging.getLogger(f"{service_name}.{module_name}")
    return logging.getLogger(service_name)


# 导出主要接口
__all__ = [
    'ServiceLoggingConfig',
    'ServiceLogger',
    'LogLevel',
    'setup_service_logging',
    'get_service_logger'
]
